package com.briup.sms.web.controller;

import com.briup.sms.utils.Result;
import com.briup.sms.utils.UploadOSSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author :xuyang
 * @DateTime:2024/1/10 9:08
 * @Version :v1.0.0
 * ClassName:FileController
 * Package  :com.briup.sms.web.controller
 * Description:TODO
 */
@RestController
@RequestMapping("/file")
@Api(tags = "文件管理相关接口")
public class FileController {
    @Autowired
    private UploadOSSUtils uploadOSSUtils;

    //文件上传到的目录路径
    @Value("${file.upload.dirPath}")
    private String dirPath;
    @Value("${file.upload.scheme}")
    private String scheme;
    @Value("${file.upload.nginxServer}")
    private String nginxServer;
    @Value("${file.upload.port}")
    private String port;
    @Value("${file.upload.baseDir}")
    private String baseDir;

    @PostMapping("/upload")
    @ApiOperation("文件上传到nginx服务器")
    public Result upload(MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        //获取唯一值
        String uuid = UUID.randomUUID().toString();
        //获取文件后缀名
        String[] arr = filename.split("[.]");
        String suffixName = arr[arr.length - 1];
        file.transferTo(new File(dirPath + uuid + "." + suffixName));
        String url = scheme + nginxServer + ":" + port + baseDir + uuid + "." + suffixName;
        return Result.success(url);
    }

    @ApiOperation("基于七牛云进行文件上传")
    @PostMapping("/uploadOss")
    public Result uploadOSS(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        String[] arr = filename.split("[.]");
        String suffixName = arr[arr.length - 1];
        String url = uploadOSSUtils.uploadOss(file, uuid + "." + suffixName);
        return Result.success(url);
    }
}

